﻿using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace FTBS.Models.DAO
{
    public class CheckOutDAO
    {
        private FilmTicketBookingSystemEntities _entities = new FilmTicketBookingSystemEntities();

        /// <summary>
        /// Generate CodeBooking
        /// </summary>
        /// <author>VuongVT</author>
        /// <returns>CartId</returns>
        public string GenerateCodeBooking()
        {
            string cartId = string.Empty;
            //2 ký tự đầu tiên: Ngày hiện tại
            string day = string.Empty;
            if (DateTime.Now.Day < 10)
            {
                day = "0" + DateTime.Now.Day.ToString();
            }
            else
            {
                day = DateTime.Now.Day.ToString();
            }
            cartId = cartId + day;

            //2 ký tự tiếp theo: Tháng
            string month = string.Empty;
            if (DateTime.Now.Month < 10)
            {
                month = "0" + DateTime.Now.Month.ToString();
            }
            else
            {
                month = DateTime.Now.Month.ToString();
            }
            cartId = cartId + month;

            //2 ký tự tiếp theo: Giờ
            string hours = string.Empty;
            if (DateTime.Now.Hour < 10)
            {
                hours = "0" + DateTime.Now.Hour.ToString();
            }
            else
            {
                hours = hours + DateTime.Now.Hour.ToString();
            }
            cartId = cartId + hours;

            //2 ký tự tiếp theo: Phút
            string minutes = string.Empty;
            if (DateTime.Now.Minute < 10)
            {
                minutes = "0" + DateTime.Now.Minute.ToString();
            }
            else
            {
                minutes = DateTime.Now.Minute.ToString();
            }
            cartId = cartId + minutes;

            //2 ký tự tiếp theo: Giây
            string second = string.Empty;
            if (DateTime.Now.Second < 10)
            {
                second = "0" + DateTime.Now.Second.ToString();
            }
            else
            {
                second = DateTime.Now.Second.ToString();
            }
            cartId = cartId + second;

            return cartId;
        }

        /// <summary>
        /// Add a cart to TicketCart table
        /// </summary>
        /// <param name="codeBooking"></param>
        /// <param name="userName"></param>
        /// <param name="totalPrice"></param>
        /// <param name="totalTicket"></param>
        /// <param name="note"></param>
        /// <param name="createTime"></param>
        /// <returns></returns>
        public string CreateCart(string userName, double totalPrice, int totalTicket, string note)
        {
            try
            {
                TicketCart ticketCart = new TicketCart();
                //CartId is auto generated
                ticketCart.CartId = GenerateCodeBooking();
                ticketCart.UserName = userName;
                ticketCart.TotalPrice = totalPrice;
                ticketCart.TotalTicket = totalTicket;
                ticketCart.Note = note;
                //CreateTime is current time
                ticketCart.CreateTime = DateTime.Now;
                _entities.TicketCarts.Add(ticketCart);
                var resultQuery = _entities.SaveChanges();
                if (resultQuery == 1)
                {
                    return ticketCart.CartId;
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Insert CartId into Ticket, change Status of Ticket to TRUE: Booked
        /// </summary>
        /// <param name="cartId"></param>
        /// <param name="chairId"></param>
        /// <param name="scheduleId"></param>
        /// <returns></returns>
        public int UpdateCartIdToTicket(string cartId, int chairId, int scheduleId)
        {
            try
            {
                var ticketItem = (from ticket in _entities.Tickets
                                  where ticket.ChairId == chairId && ticket.ScheduleId == scheduleId
                                  select ticket).FirstOrDefault();
                ticketItem.CartId = cartId;
                //Status = true is Booked
                ticketItem.Status = true;
                _entities.Entry(ticketItem).State = EntityState.Modified;
                var resultQuery = _entities.SaveChanges();
                return resultQuery;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// Check chair is booked or not
        /// </summary>
        /// <param name="listChairId"></param>
        /// <returns></returns>
        public int CheckTicketBooking(List<int> listChairId)
        {
            foreach (var chair in listChairId)
            {
                //var resultQuery = _entities.Chairs.Find(chair);
                var resultQuery = (from c in _entities.Chairs
                                   where c.ChairId == chair
                                   select c).FirstOrDefault();
                if (resultQuery.IsBooked == true)
                {
                    return 1;
                }
            }
            return 0;
        }

        /// <summary>
        /// Create Payment
        /// </summary>
        /// <param name="cartId"></param>
        /// <param name="chargeMoney"></param>
        /// <returns></returns>
        public int CreatePayment(string cartId, double chargeMoney)
        {
            try
            {
                Payment payment = new Payment();
                payment.CartId = cartId;
                payment.ChargeMoney = chargeMoney;
                payment.IsComplete = false;
                payment.IsDeleted = false;
                _entities.Payments.Add(payment);
                var resultQuery = _entities.SaveChanges();
                return resultQuery;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// Booking a Ticket method
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="totalPrice"></param>
        /// <param name="totalTicket"></param>
        /// <param name="note"></param>
        /// <param name="chairId"></param>
        /// <param name="scheduleId"></param>
        /// <returns>2: Have chair is booked
        ///          0: Don't create a booking
        ///          1: Success
        /// </returns>
        public int BookingTicket(string userName, double totalPrice, int totalTicket, string note, List<int> listChairId, int scheduleId)
        {
            try
            {
                //If have any chair is booked. Don't create a booking
                if (CheckTicketBooking(listChairId) != 0)
                {
                    return 2;
                }
                else
                {
                    //First time create TicketCart. If success, continue insert CartId into Ticket and change status of Ticket
                    string resultCreateTicketCart = CreateCart(userName, totalPrice, totalTicket, note);

                    if (!string.Empty.Equals(resultCreateTicketCart))
                    {
                        //Second time, update CartId and Status of Ticket
                        //1: Success, 0: Fail
                        foreach (var chairId in listChairId)
                        {
                            int resultUpdateTicket = UpdateCartIdToTicket(resultCreateTicketCart, chairId, scheduleId);
                            if (resultUpdateTicket == 1)
                            {
                                //Update status Booked for chair
                                int resultUpdateChair = new ChairDAO().UpdateChair(chairId);
                                if (resultUpdateChair == 0)
                                {
                                    return 0;
                                }
                            }
                            else
                            {
                                return 0;
                            }
                        }
                        //Create a Payment
                        var resultCreatePayment = CreatePayment(resultCreateTicketCart, totalPrice);
                        if (resultCreatePayment == 0)
                        {
                            return 0;
                        }
                    }
                    //Return 1: Create booking success
                    return 1;
                }
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }
}